package com.emspost;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.UUID;


public class AESUtils2 {
    private static final String ALGORITHM = "AES";

    public static String decrypt(String encryptedPhone, String secretKey) throws Exception {
        // 将 Base64 解码后的密文进行解密
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);

        byte[] decodedBytes = Base64.getDecoder().decode(encryptedPhone);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);

        return new String(decryptedBytes);
    }

    // AES 加密
    public static String encrypt(String phoneNumber, String secretKey) throws Exception {
        // 确保密钥长度为 16 字节
        SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encrypted = cipher.doFinal(phoneNumber.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static final String SECRET_KEY = "secret1234567893";

    public static void main(String[] args) throws Exception {
        String phoneNumber = "18575035924";
        // 加密
        String encryptedPhone = encrypt(phoneNumber, SECRET_KEY);
        System.out.println(phoneNumber + "Encrypted Phone: " + encryptedPhone);
//        String encryptedPhone = "18575035924";
        String decryptedPhone = decrypt(encryptedPhone, SECRET_KEY);
        System.out.println("Decrypted Phone: " + decryptedPhone);
        String substring = uuid().substring(0, 16);
        System.out.println(substring);
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("\\-" , "" );
    }
}

